//
//  TagsFactory.swift
//  CosClub
//
//  Created by iOS on 2020/3/17.
//  Copyright © 2020 ios. All rights reserved.
//

import UIKit
import QuartzCore

extension TagLabelsView {
    
   public static func calculateItemsFrame(tagsData: [String]?, space: CGFloat, type:TagLabel.TagType, contentWidth: CGFloat, newLine: Bool = false) -> [CGRect]?{
        
        var x: CGFloat = 1
        var y: CGFloat = 1
        
        guard let tagsData = tagsData else {
            return []
        }
        
        var rectList = [CGRect]()
        
        tagsData.forEach({ (string) in
            let size = string.size(withAttributes: [NSAttributedString.Key.font: UIFont.sr_system(fontSize: TagLabel.fontSize(type: type))])
            let newSize = CGSize(width: Int(size.width + TagLabel.fontSpace(type: type)),
                                 height: Int(TagLabel.height(type: type)))
            
            var rect = CGRect(origin: CGPoint(x: x, y: y), size: newSize)
            x = space + rect.maxX
            
            if x > contentWidth && newLine{
                y = y + rect.height + 8
                x = 1
                rect = CGRect(origin: CGPoint(x: x, y: y), size: newSize)
                x = space + rect.maxX
            }
            
            rectList.append(rect)
        })
        return rectList
    }
}

public class TagLabelsView: UIView {
    
    public typealias TagType = TagLabel.TagType
    
    public var space: CGFloat = 8
    public var tagList: Array<String>? = []
    public var tagType: TagType = .m_black
    private var needNewLine =  false
    
    public convenience init(space: CGFloat = 8, type: TagType, newLine: Bool = false) {
        self.init()
        self.tagType = type
        self.space = space
        self.layer.masksToBounds = true
        self.needNewLine = newLine
        
    }
    
    public override func layoutSubviews() {
        super.layoutSubviews()
        let frameListData = Self.calculateItemsFrame(tagsData: tagList, space: space, type: tagType, contentWidth: self.width, newLine: needNewLine)
        guard let frameList = frameListData, frameListData?.count == self.subviews.count else {
            return
        }
        
        for (index, element) in frameList.enumerated() {
            self.subviews[index].frame = element
        }
        
        self.height = (self.subviews.last?.frame.maxY ?? 0) + 1
        print(self.height)
    }
    
    public func reload() -> Void {
        
        for view in self.subviews {
            view.removeFromSuperview()
        }
        guard let tagList = self.tagList else {
            return
        }
        
        for value in tagList {
            addSubview(TagLabel(text: value,tagType:tagType))
        }
    }
}

// MARK: - 标签
// MARK: 不可交互
public class TagLabel : UILabel {
    
    public var borderColor: UIColor?
    public var drawString: String?
    
    private var textSize: CGSize = CGSize.zero
    
    public override init(frame: CGRect) {
        super.init(frame: frame)
        self.restorationIdentifier = "标签"
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
   public override func draw(_ rect: CGRect) {
        super.draw(rect)
        self.setNeedsLayout()
        self.layoutIfNeeded()
        
        guard let content = UIGraphicsGetCurrentContext() , let borderColor = self.borderColor else {
            return
        }
        

        let path = UIBezierPath(roundedRect: self.bounds, cornerRadius: self.bounds.height/2)

        path.lineWidth = 1
        content.setStrokeColor(borderColor.cgColor)
        path.stroke()
        
        if self.drawString != nil {
            let text = self.drawString! as NSString
            let point = CGPoint(x: (self.bounds.width - textSize.width)/2, y: (self.bounds.height - textSize.height)/2)
            text.draw(at: point, withAttributes:[NSAttributedString.Key.font: self.font!,
                                                NSAttributedString.Key.foregroundColor: self.textColor ?? UIColor.app.c3a])
        }
        
    }
}

extension TagLabel{
    
    public enum TagType {
        case s_black
        case m_gray
        case m_black
        case b_yellow
        case b_gray
        
    }
    
    public static func fontSize(type: TagType) -> CGFloat {
        switch type {
        case .s_black:
            return 10
        case .m_gray, .m_black:
            return 13
        case .b_gray, .b_yellow:
            return 14
        }
        
    }
    
    public static func fontSpace(type: TagType) -> CGFloat {
        switch type {
        case .s_black:
            return 12
        case .m_gray, .m_black:
            return 16
        case .b_gray, .b_yellow:
            return 24
        }
    }
    
    public static func height(type: TagType) -> CGFloat {
        switch type {
        case .s_black:
            return 16
        case .m_gray, .m_black:
            return 20
        case .b_gray, .b_yellow:
            return 28
        }
    }
    
    public static func textColor(type: TagType) -> UIColor {
        switch type {
        case .s_black:
            return UIColor.app.c3a
        case .m_gray:
            return UIColor.app.c3b
        case .m_black:
            return UIColor.app.c3a
        case .b_gray:
            return UIColor.app.c3a
        case .b_yellow:
            return UIColor.app.c3a
        }
    }
    
    public static func borderColor(type: TagType) -> UIColor {
        switch type {
        case .s_black:
            return UIColor.app.c3a
        case .m_gray:
            return UIColor.app.c3b
        case .m_black:
            return UIColor.app.c3a
        case .b_gray:
            return UIColor.app.c3b
        case .b_yellow:
            return UIColor.app.c1
        }
    }
    
    public convenience init(text: String ,tagType: TagType) {
        
        self.init()
        self.drawString = text
        self.font = UIFont.sr_system(fontSize: Self.fontSize(type: tagType))
        
        self.textAlignment = .center
        self.borderColor = Self.borderColor(type: tagType)
        self.textColor = Self.textColor(type: tagType)
        
        let size = text.size(withAttributes: [NSAttributedString.Key.font: UIFont.sr_system(fontSize: TagLabel.fontSize(type: tagType))])
        textSize = size
        
        self.width = size.width + Self.fontSpace(type: tagType)
        self.height = Self.height(type: tagType)
        
    }
    
    public override var text: String? {
        willSet {
            self.drawString = newValue
        }
    }
}

// MARK: 可交互
extension UIButton {
    
    public enum InterFaceTagType {
        case close
        case big
    }
    
    public convenience init(text: String ,tag: InterFaceTagType) {
        switch tag {
        case .close:
            self.init(text,fontSize:12)
            UIImage.color(UIColor.red, size: CGSize(width: 7, height: 7)){ self.setImage($0, for: .normal)}
            self.titleLabel?.text = text
            self.titleLabel?.sizeToFit()
            
            self.sizeToFit()
            self.width = self.width + 26
            self.height = 28
            
            UIImage.color(UIColor.app.c1){self.setBackgroundImage($0, for: .selected)}
            UIImage.color(UIColor.app.c3e){self.setBackgroundImage($0, for: .normal)}
            
            self.setTitleColor(UIColor.app.c3a, for: .normal)
            self.setTitleColor(UIColor.app.c3a, for: .selected)
            
            self.titleEdgeInsets = UIEdgeInsets(top: 0, left: -(self.imageView!.width + 5), bottom: 0, right: self.imageView!.width + 5)
            self.imageEdgeInsets = UIEdgeInsets(top: 0, left: 3 + self.titleLabel!.width, bottom: 0, right: -self.titleLabel!.width - 3)
            self.sr_cornerRadius = 14
            
        case .big:
            self.init(text,fontSize:14)
            self.sizeToFit()
            self.width = self.width + 16
            self.height = 20
            
            UIImage.color(UIColor.app.c1){self.setBackgroundImage($0, for: .selected)}
            UIImage.color(UIColor.app.c3b){self.setBackgroundImage($0, for: .normal)}
            self.setTitleColor(UIColor.app.c3a, for: .normal)
            self.setTitleColor(UIColor.app.c3a, for: .selected)
        }
    }
}
